<!-- 文章详情页面 -->
<template>
  <view class="detail-container">
    <!-- 文章内容 -->
    <view class="article-content" v-if="articleInfo">
      <!-- 文章标题 -->
      <view class="article-title">{{ articleInfo.title }}</view>
      
      <!-- 文章信息 -->
      <view class="article-meta">
        <view class="article-author" @click="goUserInfo(articleInfo.user_id)">
          <u-avatar :src="articleInfo.user?.avatar" size="60rpx"></u-avatar>
          <text class="author-name">{{ articleInfo.user?.nickname || '佚名' }}</text>
        </view>
        <view class="article-info">
          <text class="article-time">{{ articleInfo.create_date }}</text>
          <text class="article-views">{{ articleInfo.views }}阅读</text>
        </view>
      </view>
      
      <!-- 付费内容提示 -->
      <view class="pay-content" v-if="articleInfo.price > 0 && !articleInfo.ispaid">
        <view class="pay-tip">
          <u-icon name="lock-fill" color="#ff9900" size="40"></u-icon>
          <text>付费内容，需支付 {{ articleInfo.price }} 元查看全文</text>
        </view>
        <u-button type="warning" @click="payContent">立即支付</u-button>
      </view>
      
      <!-- 文章正文 -->
      <view class="article-body">
        <!-- 文章图片 -->
        <view class="article-image" v-if="articleInfo.image">
          <u-image :src="articleInfo.image" width="100%" height="400rpx" :fade="true"></u-image>
        </view>
        
        <!-- 文章内容 -->
        <rich-text :nodes="articleInfo.content"></rich-text>
      </view>
      
      <!-- 文章标签 -->
      <view class="article-tags" v-if="articleInfo.taglist && articleInfo.taglist.length > 0">
        <text class="tag-title">标签：</text>
        <view class="tag-list">
          <u-tag
            v-for="(tag, index) in articleInfo.taglist"
            :key="index"
            :text="tag.name"
            plain
            size="mini"
            @click="goTagList(tag.id)"
          ></u-tag>
        </view>
      </view>
      
      <!-- 下载链接 -->
      <view class="download-links" v-if="articleInfo.downloadurl && articleInfo.downloadurl.length > 0">
        <view class="download-title">下载地址：</view>
        <view class="download-list">
          <view
            class="download-item"
            v-for="(item, index) in articleInfo.downloadurl"
            :key="index"
          >
            <u-button
              type="primary"
              size="mini"
              :text="item.name + (item.password ? '（提取码：' + item.password + '）' : '')"
              @click="openUrl(item.url)"
            ></u-button>
          </view>
        </view>
      </view>
      
      <!-- 点赞区域 -->
      <view class="vote-box">
        <view class="vote-item" @click="voteArticle('like')">
          <u-icon :name="isLiked ? 'thumb-up-fill' : 'thumb-up'" :color="isLiked ? '#ff9900' : '#999'" size="40"></u-icon>
          <text :class="['vote-count', isLiked ? 'active' : '']">{{ articleInfo.likes || 0 }}</text>
        </view>
        <view class="vote-item" @click="voteArticle('dislike')">
          <u-icon :name="isDisliked ? 'thumb-down-fill' : 'thumb-down'" :color="isDisliked ? '#ff9900' : '#999'" size="40"></u-icon>
          <text :class="['vote-count', isDisliked ? 'active' : '']">{{ articleInfo.dislikes || 0 }}</text>
        </view>
        <view class="vote-item" @click="toggleCollect">
          <u-icon :name="isCollected ? 'star-fill' : 'star'" :color="isCollected ? '#ff9900' : '#999'" size="40"></u-icon>
          <text :class="['vote-count', isCollected ? 'active' : '']">收藏</text>
        </view>
        <view class="vote-item" @click="shareArticle">
          <u-icon name="share" color="#999" size="40"></u-icon>
          <text class="vote-count">分享</text>
        </view>
      </view>
    </view>
    
    <!-- 评论区域 -->
    <view class="comment-section">
      <view class="comment-header">
        <text class="comment-title">评论（{{ commentList.length || 0 }}）</text>
        <text class="comment-sort">最新</text>
      </view>
      
      <!-- 评论列表 -->
      <view class="comment-list">
        <u-empty v-if="commentList.length === 0" text="暂无评论" mode="comment"></u-empty>
        <view v-else>
          <view
            class="comment-item"
            v-for="(item, index) in commentList"
            :key="index"
          >
            <view class="comment-user">
              <u-avatar :src="item.user?.avatar" size="80rpx"></u-avatar>
              <view class="comment-user-info">
                <text class="comment-user-name">{{ item.user?.nickname || '佚名' }}</text>
                <text class="comment-time">{{ item.create_date }}</text>
              </view>
            </view>
            <view class="comment-content">{{ item.content }}</view>
            <view class="comment-actions">
              <view class="comment-action" @click="replyComment(item)">
                <u-icon name="chat" color="#999" size="28"></u-icon>
                <text>回复</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 底部评论输入框 -->
    <view class="comment-input-box">
      <u-input
        v-model="commentContent"
        placeholder="写评论..."
        border="surround"
        :disabled="!isLogin"
        @click="checkLogin"
      ></u-input>
      <u-button
        type="primary"
        size="mini"
        :disabled="!commentContent || !isLogin"
        @click="submitComment"
      >发送</u-button>
    </view>
    
    <!-- 支付弹窗 -->
    <u-popup v-model="showPayPopup" mode="bottom" border-radius="16">
      <view class="pay-popup">
        <view class="pay-popup-header">
          <text class="pay-popup-title">支付</text>
          <u-icon name="close" @click="showPayPopup = false"></u-icon>
        </view>
        <view class="pay-popup-content">
          <view class="pay-amount">
            <text>支付金额：</text>
            <text class="pay-price">{{ articleInfo?.price || 0 }}元</text>
          </view>
          <view class="pay-methods">
            <view
              class="pay-method-item"
              :class="{ active: payMethod === 'wechat' }"
              @click="payMethod = 'wechat'"
            >
              <u-icon name="weixin-fill" color="#09bb07" size="40"></u-icon>
              <text>微信支付</text>
              <u-icon v-if="payMethod === 'wechat'" name="checkmark-circle" color="#09bb07" size="40"></u-icon>
            </view>
            <view
              class="pay-method-item"
              :class="{ active: payMethod === 'alipay' }"
              @click="payMethod = 'alipay'"
            >
              <u-icon name="zhifubao-circle-fill" color="#1296db" size="40"></u-icon>
              <text>支付宝</text>
              <u-icon v-if="payMethod === 'alipay'" name="checkmark-circle" color="#1296db" size="40"></u-icon>
            </view>
            <view
              class="pay-method-item"
              :class="{ active: payMethod === 'balance' }"
              @click="payMethod = 'balance'"
            >
              <u-icon name="account" color="#ff9900" size="40"></u-icon>
              <text>余额支付</text>
              <u-icon v-if="payMethod === 'balance'" name="checkmark-circle" color="#ff9900" size="40"></u-icon>
            </view>
          </view>
          <u-button type="primary" @click="confirmPay">确认支付</u-button>
        </view>
      </view>
    </u-popup>
    
    <!-- 登录提示弹窗 -->
    <u-modal
      v-model="showLoginModal"
      title="提示"
      content="您需要登录后才能操作"
      :show-cancel-button="true"
      @confirm="goLogin"
    ></u-modal>
  </view>
</template>

<script>
import { archives, comment, collection } from '@/api/cms'

export default {
  data() {
    return {
      articleId: null,
      articleInfo: null,
      commentList: [],
      commentContent: '',
      isLogin: false,
      userInfo: null,
      isLiked: false,
      isDisliked: false,
      isCollected: false,
      showPayPopup: false,
      payMethod: 'wechat',
      showLoginModal: false,
      replyToComment: null
    }
  },
  onLoad(options) {
    if (options.id) {
      this.articleId = options.id
      this.getArticleDetail()
      this.getCommentList()
    }
    
    // 检查登录状态
    const userInfo = uni.getStorageSync('userInfo')
    if (userInfo) {
      this.isLogin = true
      this.userInfo = userInfo
    }
  },
  onShareAppMessage() {
    return {
      title: this.articleInfo?.title || 'CMS文章分享',
      path: `/pages_article/detail/index?id=${this.articleId}`
    }
  },
  methods: {
    // 获取文章详情
    async getArticleDetail() {
      try {
        const { data } = await archives.getArchivesDetail({
          id: this.articleId
        })
        if (data.code === 1) {
          this.articleInfo = data.data.archivesInfo
          
          // 设置页面标题
          uni.setNavigationBarTitle({
            title: this.articleInfo.title
          })
          
          // 检查是否已点赞或踩
          const voteStatus = uni.getStorageSync(`vote_${this.articleId}`)
          if (voteStatus === 'like') {
            this.isLiked = true
          } else if (voteStatus === 'dislike') {
            this.isDisliked = true
          }
          
          // 检查是否已收藏
          const collectStatus = uni.getStorageSync(`collect_${this.articleId}`)
          if (collectStatus === 'collected') {
            this.isCollected = true
          }
        }
      } catch (error) {
        console.error('获取文章详情失败', error)
      }
    },
    
    // 获取评论列表
    async getCommentList() {
      try {
        const { data } = await comment.getCommentList({
          aid: this.articleId
        })
        if (data.code === 1) {
          this.commentList = data.data.commentList || []
        }
      } catch (error) {
        console.error('获取评论列表失败', error)
      }
    },
    
    // 提交评论
    async submitComment() {
      if (!this.isLogin) {
        this.showLoginModal = true
        return
      }
      
      if (!this.commentContent.trim()) {
        uni.showToast({
          title: '评论内容不能为空',
          icon: 'none'
        })
        return
      }
      
      try {
        const params = {
          aid: this.articleId,
          content: this.commentContent
        }
        
        // 如果是回复评论
        if (this.replyToComment) {
          params.pid = this.replyToComment.id
        }
        
        const { data } = await comment.postComment(params)
        if (data.code === 1) {
          uni.showToast({
            title: '评论成功',
            icon: 'success'
          })
          
          // 清空评论内容
          this.commentContent = ''
          this.replyToComment = null
          
          // 重新获取评论列表
          this.getCommentList()
        } else {
          uni.showToast({
            title: data.msg || '评论失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('提交评论失败', error)
        uni.showToast({
          title: '评论失败，请稍后再试',
          icon: 'none'
        })
      }
    },
    
    // 回复评论
    replyComment(item) {
      if (!this.isLogin) {
        this.showLoginModal = true
        return
      }
      
      this.replyToComment = item
      this.commentContent = `回复 @${item.user?.nickname || '佚名'}：`
      
      // 聚焦输入框
      this.$nextTick(() => {
        const inputComponent = this.$refs.commentInput
        if (inputComponent) {
          inputComponent.focus()
        }
      })
    },
    
    // 点赞/踩文章
    async voteArticle(type) {
      if (!this.isLogin) {
        this.showLoginModal = true
        return
      }
      
      try {
        const { data } = await archives.voteArchives({
          id: this.articleId,
          type: type
        })
        if (data.code === 1) {
          if (type === 'like') {
            this.isLiked = !this.isLiked
            this.isDisliked = false
            this.articleInfo.likes = data.data.likes
            this.articleInfo.dislikes = data.data.dislikes
            
            // 保存点赞状态
            uni.setStorageSync(`vote_${this.articleId}`, this.isLiked ? 'like' : '')
          } else if (type === 'dislike') {
            this.isDisliked = !this.isDisliked
            this.isLiked = false
            this.articleInfo.likes = data.data.likes
            this.articleInfo.dislikes = data.data.dislikes
            
            // 保存点踩状态
            uni.setStorageSync(`vote_${this.articleId}`, this.isDisliked ? 'dislike' : '')
          }
          
          uni.showToast({
            title: data.msg || '操作成功',
            icon: 'success'
          })
        } else {
          uni.showToast({
            title: data.msg || '操作失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('点赞/踩文章失败', error)
        uni.showToast({
          title: '操作失败，请稍后再试',
          icon: 'none'
        })
      }
    },
    
    // 收藏/取消收藏文章
    async toggleCollect() {
      if (!this.isLogin) {
        this.showLoginModal = true
        return
      }
      
      try {
        if (this.isCollected) {
          // 取消收藏
          const { data } = await collection.deleteCollection({
            ids: this.articleId
          })
          if (data.code === 1) {
            this.isCollected = false
            uni.setStorageSync(`collect_${this.articleId}`, '')
            uni.showToast({
              title: '取消收藏成功',
              icon: 'success'
            })
          } else {
            uni.showToast({
              title: data.msg || '取消收藏失败',
              icon: 'none'
            })
          }
        } else {
          // 添加收藏
          const { data } = await collection.addCollection({
            aid: this.articleId,
            type: 'archives'
          })
          if (data.code === 1) {
            this.isCollected = true
            uni.setStorageSync(`collect_${this.articleId}`, 'collected')
            uni.showToast({
              title: '收藏成功',
              icon: 'success'
            })
          } else {
            uni.showToast({
              title: data.msg || '收藏失败',
              icon: 'none'
            })
          }
        }
      } catch (error) {
        console.error('收藏/取消收藏文章失败', error)
        uni.showToast({
          title: '操作失败，请稍后再试',
          icon: 'none'
        })
      }
    },
    
    // 支付内容
    payContent() {
      if (!this.isLogin) {
        this.showLoginModal = true
        return
      }
      
      this.showPayPopup = true
    },
    
    // 确认支付
    async confirmPay() {
      try {
        const { data } = await archives.submitOrder({
          id: this.articleId,
          paytype: this.payMethod,
          method: 'miniapp'
        })
        if (data.code === 1) {
          this.showPayPopup = false
          
          // 根据支付方式处理支付
          if (this.payMethod === 'wechat') {
            // 微信支付
            const payData = data.data.paydata
            uni.requestPayment({
              provider: 'wxpay',
              timeStamp: payData.timestamp,
              nonceStr: payData.noncestr,
              package: payData.package,
              signType: 'MD5',
              paySign: payData.sign,
              success: () => {
                uni.showToast({
                  title: '支付成功',
                  icon: 'success'
                })
                // 重新获取文章详情
                this.getArticleDetail()
              },
              fail: (err) => {
                console.error('支付失败', err)
                uni.showToast({
                  title: '支付失败',
                  icon: 'none'
                })
              }
            })
          } else if (this.payMethod === 'alipay') {
            // 支付宝支付
            uni.showToast({
              title: '暂不支持支付宝支付',
              icon: 'none'
            })
          } else if (this.payMethod === 'balance') {
            // 余额支付
            uni.showToast({
              title: '支付成功',
              icon: 'success'
            })
            // 重新获取文章详情
            this.getArticleDetail()
          }
        } else {
          uni.showToast({
            title: data.msg || '支付失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('支付失败', error)
        uni.showToast({
          title: '支付失败，请稍后再试',
          icon: 'none'
        })
      }
    },
    
    // 分享文章
    shareArticle() {
      // 在APP中可以调用系统分享
      // #ifdef APP-PLUS
      uni.share({
        provider: 'weixin',
        scene: 'WXSceneSession',
        type: 0,
        title: this.articleInfo.title,
        summary: this.articleInfo.description,
        imageUrl: this.articleInfo.image,
        href: `https://example.com/article/${this.articleId}`,
        success: function() {
          console.log('分享成功');
        },
        fail: function() {
          console.log('分享失败');
        }
      });
      // #endif
      
      // 在小程序中可以使用小程序的分享功能
      // #ifdef MP-WEIXIN
      uni.showToast({
        title: '点击右上角分享给好友',
        icon: 'none'
      })
      // #endif
      
      // 在H5中可以复制链接
      // #ifdef H5
      uni.setClipboardData({
        data: `https://example.com/article/${this.articleId}`,
        success: function() {
          uni.showToast({
            title: '链接已复制，可分享给好友',
            icon: 'none'
          })
        }
      });
      // #endif
    },
    
    // 跳转到用户信息页
    goUserInfo(userId) {
      uni.navigateTo({
        url: `/pages_mine/user/index?id=${userId}`
      })
    },
    
    // 跳转到标签列表页
    goTagList(tagId) {
      uni.navigateTo({
        url: `/pages_article/tag/index?id=${tagId}`
      })
    },
    
    // 打开URL
    openUrl(url) {
      // #ifdef H5
      window.open(url)
      // #endif
      
      // #ifndef H5
      uni.setClipboardData({
        data: url,
        success: function() {
          uni.showToast({
            title: '链接已复制到剪贴板',
            icon: 'none'
          })
        }
      });
      // #endif
    },
    
    // 检查登录状态
    checkLogin() {
      if (!this.isLogin) {
        this.showLoginModal = true
      }
    },
    
    // 跳转到登录页
    goLogin() {
      uni.navigateTo({
        url: '/pages/login/index'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.article-content {
  background-color: #ffffff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.article-title {
  font-size: 40rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 20rpx;
}

.article-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.article-author {
  display: flex;
  align-items: center;
  
  .author-name {
    margin-left: 10rpx;
    font-size: 28rpx;
    color: #333333;
  }
}

.article-info {
  font-size: 24rpx;
  color: #999999;
  
  .article-time, .article-views {
    margin-left: 20rpx;
  }
}

.pay-content {
  background-color: #fff9f0;
  border-radius: 8rpx;
  padding: 30rpx;
  margin: 20rpx 0;
  
  .pay-tip {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    
    text {
      margin-left: 10rpx;
      font-size: 28rpx;
      color: #ff9900;
    }
  }
}

.article-body {
  margin-top: 30rpx;
  font-size: 30rpx;
  line-height: 1.8;
  color: #333333;
  
  .article-image {
    margin-bottom: 30rpx;
  }
}

.article-tags {
  margin-top: 30rpx;
  display: flex;
  align-items: center;
  
  .tag-title {
    font-size: 28rpx;
    color: #666666;
    margin-right: 10rpx;
  }
  
  .tag-list {
    display: flex;
    flex-wrap: wrap;
    
    .u-tag {
      margin-right: 10rpx;
      margin-bottom: 10rpx;
    }
  }
}

.download-links {
  margin-top: 30rpx;
  
  .download-title {
    font-size: 28rpx;
    color: #666666;
    margin-bottom: 10rpx;
  }
  
  .download-list {
    display: flex;
    flex-wrap: wrap;
    
    .download-item {
      margin-right: 20rpx;
      margin-bottom: 20rpx;
    }
  }
}

.vote-box {
  display: flex;
  justify-content: space-around;
  margin-top: 50rpx;
  padding-top: 30rpx;
  border-top: 1px solid #f0f0f0;
  
  .vote-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .vote-count {
      margin-top: 10rpx;
      font-size: 24rpx;
      color: #999999;
      
      &.active {
        color: #ff9900;
      }
    }
  }
}

.comment-section {
  background-color: #ffffff;
  padding: 30rpx;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30rpx;
  
  .comment-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333333;
  }
  
  .comment-sort {
    font-size: 28rpx;
    color: #999999;
  }
}

.comment-list {
  .comment-item {
    padding: 20rpx 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
  }
}

.comment-user {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
  
  .comment-user-info {
    margin-left: 20rpx;
    
    .comment-user-name {
      font-size: 28rpx;
      color: #333333;
      margin-bottom: 5rpx;
    }
    
    .comment-time {
      font-size: 24rpx;
      color: #999999;
    }
  }
}

.comment-content {
  font-size: 28rpx;
  color: #333333;
  line-height: 1.6;
  margin: 10rpx 0;
  padding-left: 100rpx;
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
  
  .comment-action {
    display: flex;
    align-items: center;
    margin-left: 30rpx;
    
    text {
      margin-left: 5rpx;
      font-size: 24rpx;
      color: #999999;
    }
  }
}

.comment-input-box {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #ffffff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .u-input {
    flex: 1;
    margin-right: 20rpx;
  }
}

.pay-popup {
  padding: 30rpx;
  
  .pay-popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    
    .pay-popup-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333333;
    }
  }
  
  .pay-popup-content {
    .pay-amount {
      display: flex;
      align-items: center;
      margin-bottom: 30rpx;
      
      text {
        font-size: 28rpx;
        color: #333333;
      }
      
      .pay-price {
        font-size: 36rpx;
        color: #ff9900;
        font-weight: bold;
      }
    }
    
    .pay-methods {
      margin-bottom: 30rpx;
      
      .pay-method-item {
        display: flex;
        align-items: center;
        padding: 20rpx 0;
        border-bottom: 1px solid #f0f0f0;
        
        text {
          flex: 1;
          margin-left: 20rpx;
          font-size: 28rpx;
          color: #333333;
        }
        
        &.active {
          background-color: #f8f8f8;
        }
      }
    }
  }
}
</style>